using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using AvaloniaDrawingPad.Models;
using AvaloniaDrawingPad.Models.Commands;
using AvaloniaDrawingPad.Views;
using MsBox.Avalonia;
using MsBox.Avalonia.Enums;

namespace AvaloniaDrawingPad;

public partial class MainWindow : Window
{
    // 绘图状态
    private bool _isDrawing = false;
    private Point _startPoint;
    private Point _lastPoint;
    private DrawingMode _currentMode = DrawingMode.Pen;
    private IBrush _currentBrush = Brushes.Black;
    private double _currentThickness = 2;
    private Shape? _currentShape = null; // 当前正在绘制的图形
    
    // 画笔路径相关
    private List<Line> _currentStroke = new List<Line>(); // 当前绘制的一笔中的所有线段
    
    // 图层管理
    private LayerManager _layerManager;
    
    // 可选择图形管理
    private List<SelectableShape> _selectableShapes = new List<SelectableShape>();
    private SelectableShape? _selectedShape = null;
    
    // 快捷键管理
    private ShortcutManager _shortcutManager;
    
    // 添加项目管理器实例
    private ProjectManager _projectManager;
    
    // 添加命令管理器实例
    private CommandManager _commandManager;
    
    // 绘图模式枚举
    private enum DrawingMode
    {
        Pen,
        Eraser,
        Line,
        Rectangle,
        Ellipse,
        Select
    }
    
    public MainWindow()
    {
        InitializeComponent();
        
        // 初始化图层管理器
        _layerManager = new LayerManager(MainCanvas);
        LayerListBox.ItemsSource = _layerManager.Layers;
        
        // 初始化快捷键管理器
        _shortcutManager = ShortcutManager.Instance;
        
        // 初始化命令管理器
        _commandManager = CommandManager.Instance;
        _commandManager.StateChanged += CommandManager_StateChanged;
        
        // 初始化项目管理器，使用ZIP格式
        _projectManager = new ProjectManager(_layerManager, MainCanvas, _selectableShapes);
        _projectManager.UseZipFormat = true; // 使用ZIP格式
        
        // 设置项目管理器的选中事件处理器
        _projectManager.SelectionChangedHandler = Shape_SelectionChanged;
        
        // 初始化状态
        StatusText.Text = "就绪 - 画笔模式";
        PenButton.IsEnabled = false; // 默认选中画笔
        
        // 初始化删除按钮状态
        UpdateDeleteButtonState();
        
        // 添加键盘事件处理
        KeyDown += MainWindow_KeyDown;
        
        // 初始化撤销/重做按钮状态
        UpdateUndoRedoState();
    }
    
    // 键盘事件处理
    private void MainWindow_KeyDown(object? sender, KeyEventArgs e)
    {
        // 查找匹配的快捷键
        var shortcut = _shortcutManager.FindShortcut(e.Key, e.KeyModifiers);
        if (shortcut != null)
        {
            // 执行对应的操作
            switch (shortcut.Name)
            {
                case "画笔":
                    PenButton_Click(null, null);
                    break;
                case "橡皮擦":
                    EraserButton_Click(null, null);
                    break;
                case "直线":
                    LineButton_Click(null, null);
                    break;
                case "矩形":
                    RectangleButton_Click(null, null);
                    break;
                case "圆形":
                    EllipseButton_Click(null, null);
                    break;
                case "选择":
                    SelectButton_Click(null, null);
                    break;
                case "删除":
                    DeleteButton_Click(null, null);
                    break;
                case "保存":
                    SaveProject_Click(null, null);
                    break;
                case "导入图片":
                    ImportImageButton_Click(null, null);
                    break;
                case "清空画布":
                    ClearButton_Click(null, null);
                    break;
                case "添加图层":
                    AddLayerButton_Click(null, null);
                    break;
                case "上移图层":
                    MoveLayerUpButton_Click(null, null);
                    break;
                case "下移图层":
                    MoveLayerDownButton_Click(null, null);
                    break;
                case "显示快捷键":
                    ShortcutsButton_Click(null, null);
                    break;
                case "撤销":
                    Undo_Click(null, null);
                    break;
                case "重做":
                    Redo_Click(null, null);
                    break;
            }
            
            e.Handled = true;
        }
        // 检查常见的文件操作快捷键
        else if (e.KeyModifiers.HasFlag(KeyModifiers.Control))
        {
            switch (e.Key)
            {
                case Key.N: // Ctrl+N 新建项目
                    NewProject_Click(null, null);
                    e.Handled = true;
                    break;
                case Key.O: // Ctrl+O 打开项目
                    OpenProject_Click(null, null);
                    e.Handled = true;
                    break;
                case Key.S when e.KeyModifiers.HasFlag(KeyModifiers.Shift): // Ctrl+Shift+S 另存为
                    SaveProjectAs_Click(null, null);
                    e.Handled = true;
                    break;
                case Key.S: // Ctrl+S 保存项目
                    SaveProject_Click(null, null);
                    e.Handled = true;
                    break;
                case Key.Z: // Ctrl+Z 撤销
                    Undo_Click(null, null);
                    e.Handled = true;
                    break;
                case Key.Y: // Ctrl+Y 重做
                    Redo_Click(null, null);
                    e.Handled = true;
                    break;
            }
        }
    }
    
    // 更新删除按钮状态
    private void UpdateDeleteButtonState()
    {
        DeleteButton.IsEnabled = _selectedShape != null;
    }
    
    // 重置所有按钮状态
    private void ResetButtonStates()
    {
        PenButton.IsEnabled = true;
        EraserButton.IsEnabled = true;
        LineButton.IsEnabled = true;
        RectangleButton.IsEnabled = true;
        EllipseButton.IsEnabled = true;
        SelectButton.IsEnabled = true;
    }
    
    // 画笔按钮点击事件
    private void PenButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Pen;
        StatusText.Text = "就绪 - 画笔模式";
        PenButton.IsEnabled = false;
        UnselectAllShapes();
        
        // 禁用图形选择功能
        SetShapesSelectionEnabled(false);
    }
    
    // 橡皮擦按钮点击事件
    private void EraserButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Eraser;
        StatusText.Text = "就绪 - 橡皮擦模式";
        EraserButton.IsEnabled = false;
        UnselectAllShapes();
        
        // 禁用图形选择功能
        SetShapesSelectionEnabled(false);
    }
    
    // 直线按钮点击事件
    private void LineButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Line;
        StatusText.Text = "就绪 - 直线模式";
        LineButton.IsEnabled = false;
        UnselectAllShapes();
        
        // 禁用图形选择功能
        SetShapesSelectionEnabled(false);
    }
    
    // 矩形按钮点击事件
    private void RectangleButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Rectangle;
        StatusText.Text = "就绪 - 矩形模式";
        RectangleButton.IsEnabled = false;
        UnselectAllShapes();
        
        // 禁用图形选择功能
        SetShapesSelectionEnabled(false);
    }
    
    // 圆形按钮点击事件
    private void EllipseButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Ellipse;
        StatusText.Text = "就绪 - 圆形模式";
        EllipseButton.IsEnabled = false;
        UnselectAllShapes();
        
        // 禁用图形选择功能
        SetShapesSelectionEnabled(false);
    }
    
    // 选择按钮点击事件
    private void SelectButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        ResetButtonStates();
        _currentMode = DrawingMode.Select;
        StatusText.Text = "就绪 - 选择模式";
        SelectButton.IsEnabled = false;
        
        // 启用图形选择功能
        SetShapesSelectionEnabled(true);
    }
    
    // 删除选中按钮点击事件
    private void DeleteButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        DeleteSelectedShape();
    }
    
    // 快捷键按钮点击事件
    private void ShortcutsButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        var shortcutWindow = new ShortcutSettingsWindow();
        shortcutWindow.ShowDialog(this);
    }
    
    // 删除选中的图形
    private void DeleteSelectedShape()
    {
        if (_selectedShape != null && _layerManager.SelectedLayer != null)
        {
            Console.WriteLine($"准备删除选中图形，类型：{_selectedShape.Element.GetType().Name}");
            
            // 创建删除命令
            var deleteCommand = new DeleteShapeCommand(
                _layerManager.SelectedLayer,
                _selectedShape.Element,
                _selectedShape,
                _layerManager,
                _selectableShapes,
                () => {
                    // 清除选中状态
                    _selectedShape = null;
                    
                    // 更新删除按钮状态
                    UpdateDeleteButtonState();
                    
                    StatusText.Text = "已删除选中图形";
                }
            );
            
            // 执行删除命令
            _commandManager.ExecuteCommand(deleteCommand);
        }
        else
        {
            Console.WriteLine("没有选中的图形，无法删除");
        }
    }
    
    // 清空按钮点击事件
    private void ClearButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        _layerManager.ClearSelectedLayer();
        _selectableShapes.Clear();
        _selectedShape = null;
        UpdateDeleteButtonState();
        TempCanvas.Children.Clear();
        StatusText.Text = "画布已清空";
    }
    
    // 导入图片按钮点击事件
    private async void ImportImageButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        await ImportImageAsync();
    }
    
    // 导入图片
    private async Task ImportImageAsync()
    {
        try
        {
            // 获取打开文件对话框
            var storageProvider = StorageProvider;
            var filePickerOptions = new FilePickerOpenOptions
            {
                Title = "选择图片",
                AllowMultiple = false,
                FileTypeFilter = new[]
                {
                    new FilePickerFileType("图片文件")
                    {
                        Patterns = new[] { "*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif" },
                        MimeTypes = new[] { "image/jpeg", "image/png", "image/bmp", "image/gif" }
                    }
                }
            };

            var result = await storageProvider.OpenFilePickerAsync(filePickerOptions);
            
            if (result != null && result.Count > 0)
            {
                var file = result[0];
                using var stream = await file.OpenReadAsync();
                var bitmap = new Bitmap(stream);
                
                // 创建图片控件
                var image = new Image
                {
                    Source = bitmap,
                    Width = bitmap.Size.Width,
                    Height = bitmap.Size.Height,
                    Stretch = Stretch.Uniform
                };
                
                // 添加到当前选中的图层
                if (_layerManager.SelectedLayer != null)
                {
                    Canvas.SetLeft(image, 10);
                    Canvas.SetTop(image, 10);
                    
                    // 创建可选择图形
                    var selectableImage = new SelectableShape(_layerManager.SelectedLayer.Content, image);
                    selectableImage.SelectionEnabled = _currentMode == DrawingMode.Select;
                    
                    // 设置移动和调整大小的命令回调
                    selectableImage.MoveCommandCallback = (shape, oldLeft, oldTop, newLeft, newTop) => {
                        var command = new MoveShapeCommand(shape, oldLeft, oldTop, newLeft, newTop, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    selectableImage.ResizeCommandCallback = (shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight) => {
                        var command = new ResizeShapeCommand(shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    // 使用命令模式添加图形
                    var addCommand = new AddShapeCommand(
                        _layerManager.SelectedLayer, 
                        image, 
                        selectableImage, 
                        _layerManager,
                        (shape) => {
                            _selectableShapes.Add(shape);
                            shape.SelectionChanged += Shape_SelectionChanged;
                            
                            // 自动选择新导入的图片
                            if (_currentMode == DrawingMode.Select)
                            {
                                UnselectAllShapes();
                                _selectedShape = shape;
                                _selectedShape.IsSelected = true;
                                UpdateDeleteButtonState();
                            }
                        });
                    
                    _commandManager.ExecuteCommand(addCommand);
                    
                    StatusText.Text = $"已导入图片: {file.Name}";
                }
            }
        }
        catch (Exception ex)
        {
            StatusText.Text = $"导入图片失败: {ex.Message}";
        }
    }
    
    // 新建项目
    private async void NewProject_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        // 检查是否有未保存的更改
        if (_projectManager.HasUnsavedChanges)
        {
            bool shouldContinue = await ConfirmUnsavedChanges();
            if (!shouldContinue)
                return; // 用户取消操作
        }
        
        // 创建新项目
        _projectManager.NewProject();
        
        // 更新界面
        LayerListBox.ItemsSource = null;
        LayerListBox.ItemsSource = _layerManager.Layers;
        
        // 更新UI
        StatusText.Text = "已创建新项目";
    }
    
    // 打开项目
    private async void OpenProject_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        // 检查是否有未保存的更改
        if (_projectManager.HasUnsavedChanges)
        {
            bool shouldContinue = await ConfirmUnsavedChanges();
            if (!shouldContinue)
                return; // 用户取消操作
        }
        
        // 打开文件选择对话框
        var storageProvider = StorageProvider;
        var filePickerOptions = new FilePickerOpenOptions
        {
            Title = "打开项目",
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType("绘图应用项目")
                {
                    Patterns = new[] { $"*{_projectManager.DefaultFileExtension}" },
                    MimeTypes = new[] { "application/zip" }
                }
            }
        };

        var result = await storageProvider.OpenFilePickerAsync(filePickerOptions);
        
        if (result != null && result.Count > 0)
        {
            var file = result[0];
            
            try
            {
                // 获取文件路径并加载项目
                string filePath = file.Path.LocalPath;
                bool success = await _projectManager.LoadProjectAsync(filePath);
                
                if (success)
                {
                    // 更新UI
                    StatusText.Text = $"已打开项目: {System.IO.Path.GetFileName(filePath)}";
                    
                    // 重新绑定图层列表
                    LayerListBox.ItemsSource = null;
                    LayerListBox.ItemsSource = _layerManager.Layers;
                }
                else
                {
                    ShowErrorMessage("打开失败", "无法打开项目文件，可能格式不正确或文件已损坏。");
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("错误", $"打开项目时发生错误: {ex.Message}");
            }
        }
    }
    
    // 保存项目
    private async void SaveProject_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        await SaveCurrentProject();
    }
    
    // 另存为
    private async void SaveProjectAs_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        await SaveProjectAsAsync();
    }
    
    // 保存当前项目
    private async Task<bool> SaveCurrentProject()
    {
        try
        {
            // 如果没有当前项目路径，执行"另存为"操作
            if (_projectManager.CurrentProjectPath == null)
            {
                return await SaveProjectAsAsync();
            }
            
            // 保存项目
            bool success = await _projectManager.SaveProjectAsync();
            
            if (success)
            {
                StatusText.Text = $"项目已保存: {System.IO.Path.GetFileName(_projectManager.CurrentProjectPath)}";
                return true;
            }
            else
            {
                ShowErrorMessage("保存失败", "保存项目时发生错误。");
                return false;
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("错误", $"保存项目时发生错误: {ex.Message}");
            return false;
        }
    }
    
    // 项目另存为
    private async Task<bool> SaveProjectAsAsync()
    {
        try
        {
            // 打开保存文件对话框
            var storageProvider = StorageProvider;
            var saveFileDialog = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
            {
                Title = "保存项目",
                SuggestedFileName = $"绘图_{DateTime.Now:yyyyMMdd_HHmmss}{_projectManager.DefaultFileExtension}",
                FileTypeChoices = new[]
                {
                    new FilePickerFileType(_projectManager.FileTypeDescription)
                    {
                        Patterns = new[] { $"*{_projectManager.DefaultFileExtension}" },
                        MimeTypes = new[] { "application/zip" }
                    }
                }
            });

            if (saveFileDialog != null)
            {
                // 获取文件路径并保存项目
                string filePath = saveFileDialog.Path.LocalPath;
                
                // 确保文件扩展名正确
                if (!filePath.EndsWith(_projectManager.DefaultFileExtension))
                {
                    filePath += _projectManager.DefaultFileExtension;
                }
                
                bool success = await _projectManager.SaveProjectAsync(filePath);
                
                if (success)
                {
                    StatusText.Text = $"项目已保存: {System.IO.Path.GetFileName(filePath)}";
                    return true;
                }
                else
                {
                    ShowErrorMessage("保存失败", "保存项目时发生错误。");
                    return false;
                }
            }
            
            return false; // 用户取消保存
        }
        catch (Exception ex)
        {
            ShowErrorMessage("错误", $"保存项目时发生错误: {ex.Message}");
            return false;
        }
    }
    
    // 在图形创建后标记项目有未保存的更改
    private void MarkProjectChanged()
    {
        _projectManager?.MarkAsChanged();
    }
    
    // 画布鼠标按下事件
    private void DrawingCanvas_PointerPressed(object? sender, PointerPressedEventArgs e)
    {
        if (_layerManager.SelectedLayer == null)
            return;
            
        _isDrawing = true;
        _startPoint = e.GetPosition(MainCanvas);
        _lastPoint = _startPoint;
        
        // 如果在选择模式下，尝试选择图形
        if (_currentMode == DrawingMode.Select)
        {
            bool hitShape = false;
            
            // 先检查是否点击了已选择的图形
            if (_selectedShape != null && _selectedShape.HitTest(_startPoint))
            {
                hitShape = true;
                // 已经选中，不需要做任何事
                StatusText.Text = "正在移动图形...";
            }
            else
            {
                // 尝试选择其他图形
                foreach (var selectableShape in _selectableShapes)
                {
                    Console.WriteLine($"测试图形: {selectableShape.Element.GetType().Name}");
                    bool hit = selectableShape.HitTest(_startPoint);
                    Console.WriteLine($"HitTest结果: {hit}");
                    
                    if (hit)
                    {
                        hitShape = true;
                        UnselectAllShapes();
                        _selectedShape = selectableShape;
                        _selectedShape.IsSelected = true;
                        UpdateDeleteButtonState();
                        StatusText.Text = $"已选择图形: {_selectedShape.Element.GetType().Name}";
                        Console.WriteLine($"选中图形: {_selectedShape.Element.GetType().Name}");
                        break;
                    }
                }
            }
            
            // 如果没有点击任何图形，取消所有选择
            if (!hitShape)
            {
                UnselectAllShapes();
                UpdateDeleteButtonState();
                StatusText.Text = "就绪 - 选择模式";
            }
            
            e.Handled = true;
            return;
        }
        
        // 非选择模式下，取消所有选择
        UnselectAllShapes();
        UpdateDeleteButtonState();
        
        switch (_currentMode)
        {
            case DrawingMode.Pen:
                StatusText.Text = "正在绘制...";
                
                // 清空当前笔画
                _currentStroke.Clear();
                
                // 调试信息
                Console.WriteLine($"开始绘制，起始点：{_startPoint}");
                break;
            case DrawingMode.Eraser:
                StatusText.Text = "正在擦除...";
                break;
            case DrawingMode.Line:
                // 创建临时直线
                _currentShape = new Line
                {
                    StartPoint = _startPoint,
                    EndPoint = _startPoint,
                    Stroke = _currentBrush,
                    StrokeThickness = _currentThickness,
                    StrokeLineCap = PenLineCap.Round
                };
                TempCanvas.Children.Add(_currentShape);
                StatusText.Text = "正在绘制直线...";
                break;
            case DrawingMode.Rectangle:
                // 创建临时矩形
                _currentShape = new Rectangle
                {
                    Stroke = _currentBrush,
                    StrokeThickness = _currentThickness,
                    Fill = FillShapeCheckBox.IsChecked == true ? _currentBrush : null
                };
                Canvas.SetLeft(_currentShape, _startPoint.X);
                Canvas.SetTop(_currentShape, _startPoint.Y);
                _currentShape.Width = 0;
                _currentShape.Height = 0;
                TempCanvas.Children.Add(_currentShape);
                StatusText.Text = "正在绘制矩形...";
                break;
            case DrawingMode.Ellipse:
                // 创建临时椭圆
                _currentShape = new Ellipse
                {
                    Stroke = _currentBrush,
                    StrokeThickness = _currentThickness,
                    Fill = FillShapeCheckBox.IsChecked == true ? _currentBrush : null
                };
                Canvas.SetLeft(_currentShape, _startPoint.X);
                Canvas.SetTop(_currentShape, _startPoint.Y);
                _currentShape.Width = 0;
                _currentShape.Height = 0;
                TempCanvas.Children.Add(_currentShape);
                StatusText.Text = "正在绘制圆形...";
                break;
        }
    }
    
    // 画布鼠标释放事件
    private void DrawingCanvas_PointerReleased(object? sender, PointerReleasedEventArgs e)
    {
        if (!_isDrawing || _layerManager.SelectedLayer == null)
            return;
        
        _isDrawing = false;
        
        // 处理不同绘图模式的结束操作
        if (_currentMode == DrawingMode.Pen)
        {
            // 如果有线段，创建一个Canvas包含所有线段，并使其可选择
            if (_currentStroke.Count > 0)
            {
                // 计算边界框
                double minX = _currentStroke.Min(line => Math.Min(line.StartPoint.X, line.EndPoint.X));
                double minY = _currentStroke.Min(line => Math.Min(line.StartPoint.Y, line.EndPoint.Y));
                double maxX = _currentStroke.Max(line => Math.Max(line.StartPoint.X, line.EndPoint.X));
                double maxY = _currentStroke.Max(line => Math.Max(line.StartPoint.Y, line.EndPoint.Y));
                double width = maxX - minX;
                double height = maxY - minY;
                
                // 创建一个Canvas来包含所有线段
                var strokeCanvas = new Canvas
                {
                    Width = width,
                    Height = height,
                    Background = Brushes.Transparent
                };
                
                Canvas.SetLeft(strokeCanvas, minX);
                Canvas.SetTop(strokeCanvas, minY);
                
                // 从图层中移除所有线段，并添加到strokeCanvas
                foreach (var line in _currentStroke)
                {
                    _layerManager.SelectedLayer.Content.Children.Remove(line);
                    
                    // 创建新线段，调整坐标
                    var newLine = new Line
                    {
                        StartPoint = new Point(line.StartPoint.X - minX, line.StartPoint.Y - minY),
                        EndPoint = new Point(line.EndPoint.X - minX, line.EndPoint.Y - minY),
                        Stroke = line.Stroke,
                        StrokeThickness = line.StrokeThickness,
                        StrokeLineCap = line.StrokeLineCap
                    };
                    
                    // 添加到strokeCanvas
                    strokeCanvas.Children.Add(newLine);
                }
                
                // 添加strokeCanvas到图层
                _layerManager.SelectedLayer.Content.Children.Add(strokeCanvas);
                
                // 添加到可选择图形列表
                var selectableStroke = new SelectableShape(_layerManager.SelectedLayer.Content, strokeCanvas);
                selectableStroke.SelectionEnabled = _currentMode == DrawingMode.Select;
                
                // 设置移动和调整大小的命令回调
                selectableStroke.MoveCommandCallback = (shape, oldLeft, oldTop, newLeft, newTop) => {
                    var command = new MoveShapeCommand(shape, oldLeft, oldTop, newLeft, newTop, _layerManager);
                    _commandManager.ExecuteCommand(command);
                };
                
                selectableStroke.ResizeCommandCallback = (shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight) => {
                    var command = new ResizeShapeCommand(shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight, _layerManager);
                    _commandManager.ExecuteCommand(command);
                };
                
                // 使用命令模式添加图形
                var addCommand = new AddShapeCommand(
                    _layerManager.SelectedLayer, 
                    strokeCanvas, 
                    selectableStroke, 
                    _layerManager,
                    (shape) => {
                        _selectableShapes.Add(shape);
                        shape.SelectionChanged += Shape_SelectionChanged;
                    });
                
                _commandManager.ExecuteCommand(addCommand);
                
                // 订阅选中事件
                selectableStroke.SelectionChanged += Shape_SelectionChanged;
                
                // 调试信息
                Console.WriteLine($"画笔路径完成，线段数：{_currentStroke.Count}");
                
                // 清除当前笔画
                _currentStroke.Clear();
            }
            else
            {
                Console.WriteLine("画笔路径无效或为空");
            }
            
            // 标记项目已更改
            MarkProjectChanged();
        }
        else if (_currentMode == DrawingMode.Line || _currentMode == DrawingMode.Rectangle || _currentMode == DrawingMode.Ellipse)
        {
            // 从临时画布移除当前图形
            if (_currentShape != null)
            {
                TempCanvas.Children.Remove(_currentShape);
                
                // 如果是线条，创建一个新的线条添加到图层
                if (_currentShape is Line line)
                {
                    var newLine = new Line
                    {
                        StartPoint = line.StartPoint,
                        EndPoint = line.EndPoint,
                        Stroke = line.Stroke,
                        StrokeThickness = line.StrokeThickness,
                        StrokeLineCap = line.StrokeLineCap
                    };
                    
                    // 创建可选择图形
                    var selectableShape = new SelectableShape(_layerManager.SelectedLayer.Content, newLine);
                    selectableShape.SelectionEnabled = _currentMode == DrawingMode.Select;
                    
                    // 设置移动和调整大小的命令回调
                    selectableShape.MoveCommandCallback = (shape, oldLeft, oldTop, newLeft, newTop) => {
                        var command = new MoveShapeCommand(shape, oldLeft, oldTop, newLeft, newTop, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    selectableShape.ResizeCommandCallback = (shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight) => {
                        var command = new ResizeShapeCommand(shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    // 使用命令模式添加图形
                    var addCommand = new AddShapeCommand(
                        _layerManager.SelectedLayer, 
                        newLine, 
                        selectableShape, 
                        _layerManager,
                        (shape) => {
                            _selectableShapes.Add(shape);
                            shape.SelectionChanged += Shape_SelectionChanged;
                            
                            // 如果是选择模式，自动选择新创建的图形
                            if (_currentMode == DrawingMode.Select)
                            {
                                UnselectAllShapes();
                                _selectedShape = shape;
                                _selectedShape.IsSelected = true;
                                UpdateDeleteButtonState();
                            }
                        });
                    
                    _commandManager.ExecuteCommand(addCommand);
                }
                else
                {
                    // 如果是其他形状，复制属性并添加到图层
                    Shape newShape;
                    
                    if (_currentShape is Rectangle rect)
                    {
                        newShape = new Rectangle
                        {
                            Width = rect.Width,
                            Height = rect.Height,
                            Stroke = rect.Stroke,
                            StrokeThickness = rect.StrokeThickness,
                            Fill = rect.Fill
                        };
                        
                        Canvas.SetLeft(newShape, Canvas.GetLeft(rect));
                        Canvas.SetTop(newShape, Canvas.GetTop(rect));
                    }
                    else if (_currentShape is Ellipse ellipse)
                    {
                        newShape = new Ellipse
                        {
                            Width = ellipse.Width,
                            Height = ellipse.Height,
                            Stroke = ellipse.Stroke,
                            StrokeThickness = ellipse.StrokeThickness,
                            Fill = ellipse.Fill
                        };
                        
                        Canvas.SetLeft(newShape, Canvas.GetLeft(ellipse));
                        Canvas.SetTop(newShape, Canvas.GetTop(ellipse));
                    }
                    else
                    {
                        // 未知形状，不处理
                        TempCanvas.Children.Clear();
                        _currentShape = null;
                        return;
                    }
                    
                    // 创建可选择图形
                    var selectableShape = new SelectableShape(_layerManager.SelectedLayer.Content, newShape);
                    selectableShape.SelectionEnabled = _currentMode == DrawingMode.Select;
                    
                    // 设置移动和调整大小的命令回调
                    selectableShape.MoveCommandCallback = (shape, oldLeft, oldTop, newLeft, newTop) => {
                        var command = new MoveShapeCommand(shape, oldLeft, oldTop, newLeft, newTop, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    selectableShape.ResizeCommandCallback = (shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight) => {
                        var command = new ResizeShapeCommand(shape, oldLeft, oldTop, oldWidth, oldHeight, newLeft, newTop, newWidth, newHeight, _layerManager);
                        _commandManager.ExecuteCommand(command);
                    };
                    
                    // 使用命令模式添加图形
                    var addCommand = new AddShapeCommand(
                        _layerManager.SelectedLayer, 
                        newShape, 
                        selectableShape, 
                        _layerManager,
                        (shape) => {
                            _selectableShapes.Add(shape);
                            shape.SelectionChanged += Shape_SelectionChanged;
                            
                            // 如果是选择模式，自动选择新创建的图形
                            if (_currentMode == DrawingMode.Select)
                            {
                                UnselectAllShapes();
                                _selectedShape = shape;
                                _selectedShape.IsSelected = true;
                                UpdateDeleteButtonState();
                            }
                        });
                    
                    _commandManager.ExecuteCommand(addCommand);
                }
            }
            
            // 标记项目已更改
            MarkProjectChanged();
        }
        
        // 清除临时画布
        TempCanvas.Children.Clear();
        _currentShape = null;
        
        switch (_currentMode)
        {
            case DrawingMode.Pen:
                StatusText.Text = "就绪 - 画笔模式";
                break;
            case DrawingMode.Eraser:
                StatusText.Text = "就绪 - 橡皮擦模式";
                break;
            case DrawingMode.Line:
                StatusText.Text = "就绪 - 直线模式";
                break;
            case DrawingMode.Rectangle:
                StatusText.Text = "就绪 - 矩形模式";
                break;
            case DrawingMode.Ellipse:
                StatusText.Text = "就绪 - 圆形模式";
                break;
            case DrawingMode.Select:
                StatusText.Text = "就绪 - 选择模式";
                break;
        }
    }
    
    // 画布鼠标移动事件
    private void DrawingCanvas_PointerMoved(object? sender, PointerEventArgs e)
    {
        if (!_isDrawing || _layerManager.SelectedLayer == null)
            return;
        
        Point currentPoint = e.GetPosition(MainCanvas);
        
        switch (_currentMode)
        {
            case DrawingMode.Pen:
                // 创建新线段
                var newLine = new Line
                {
                    StartPoint = _lastPoint,
                    EndPoint = currentPoint,
                    Stroke = _currentBrush,
                    StrokeThickness = _currentThickness,
                    StrokeLineCap = PenLineCap.Round
                };
                
                // 添加到当前图层
                _layerManager.SelectedLayer.Content.Children.Add(newLine);
                
                // 添加到当前笔画
                _currentStroke.Add(newLine);
                
                // 调试信息
                Console.WriteLine($"添加线段：{_lastPoint} -> {currentPoint}");
                
                // 更新上一个点
                _lastPoint = currentPoint;
                break;
                
            case DrawingMode.Eraser:
                // 创建橡皮擦线条（白色）
                var eraserLine = new Line
                {
                    StartPoint = _lastPoint,
                    EndPoint = currentPoint,
                    Stroke = Brushes.White,
                    StrokeThickness = _currentThickness * 2,
                    StrokeLineCap = PenLineCap.Round
                };
                
                // 添加到当前图层
                _layerManager.SelectedLayer.Content.Children.Add(eraserLine);
                
                // 更新上一个点
                _lastPoint = currentPoint;
                break;
                
            case DrawingMode.Line:
                // 更新临时直线
                if (_currentShape is Line shapeLine)
                {
                    shapeLine.EndPoint = currentPoint;
                }
                break;
                
            case DrawingMode.Rectangle:
                // 更新临时矩形
                if (_currentShape is Rectangle)
                {
                    double left = Math.Min(_startPoint.X, currentPoint.X);
                    double top = Math.Min(_startPoint.Y, currentPoint.Y);
                    double width = Math.Abs(currentPoint.X - _startPoint.X);
                    double height = Math.Abs(currentPoint.Y - _startPoint.Y);
                    
                    Canvas.SetLeft(_currentShape, left);
                    Canvas.SetTop(_currentShape, top);
                    _currentShape.Width = width;
                    _currentShape.Height = height;
                }
                break;
                
            case DrawingMode.Ellipse:
                // 更新临时椭圆
                if (_currentShape is Ellipse)
                {
                    double left = Math.Min(_startPoint.X, currentPoint.X);
                    double top = Math.Min(_startPoint.Y, currentPoint.Y);
                    double width = Math.Abs(currentPoint.X - _startPoint.X);
                    double height = Math.Abs(currentPoint.Y - _startPoint.Y);
                    
                    Canvas.SetLeft(_currentShape, left);
                    Canvas.SetTop(_currentShape, top);
                    _currentShape.Width = width;
                    _currentShape.Height = height;
                }
                break;
        }
    }
    
    // 取消所有图形的选择
    private void UnselectAllShapes()
    {
        foreach (var shape in _selectableShapes)
        {
            shape.IsSelected = false;
        }
        _selectedShape = null;
    }
    
    // 图层列表选择变更事件
    private void LayerListBox_SelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (LayerListBox.SelectedItem is Layer layer)
        {
            _layerManager.SelectedLayer = layer;
            StatusText.Text = $"已选择图层: {layer.Name}";
        }
    }
    
    // 图层可见性点击事件
    private void LayerVisibility_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        if (e.Source is CheckBox checkBox && checkBox.DataContext is Layer layer)
        {
            _layerManager.ToggleLayerVisibility(layer);
        }
    }
    
    // 移除图层点击事件
    private void RemoveLayer_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        if (e.Source is Button button && button.DataContext is Layer layer)
        {
            _layerManager.RemoveLayer(layer);
        }
    }
    
    // 添加图层按钮点击事件
    private void AddLayerButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        var layer = _layerManager.AddLayer($"图层 {_layerManager.Layers.Count + 1}");
        StatusText.Text = $"已添加图层: {layer.Name}";
    }
    
    // 上移图层按钮点击事件
    private void MoveLayerUpButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        if (_layerManager.SelectedLayer != null)
        {
            _layerManager.MoveLayerUp(_layerManager.SelectedLayer);
        }
    }
    
    // 下移图层按钮点击事件
    private void MoveLayerDownButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        if (_layerManager.SelectedLayer != null)
        {
            _layerManager.MoveLayerDown(_layerManager.SelectedLayer);
        }
    }

    protected override void OnLoaded(Avalonia.Interactivity.RoutedEventArgs e)
    {
        base.OnLoaded(e);
        
        // 添加鼠标右键点击事件
        MainCanvas.PointerReleased += MainCanvas_PointerReleased;
    }
    
    private void MainCanvas_PointerReleased(object? sender, PointerReleasedEventArgs e)
    {
        // 仅处理鼠标右键
        if (e.InitialPressMouseButton != MouseButton.Right)
            return;
            
        Point position = e.GetPosition(MainCanvas);
        Console.WriteLine($"鼠标右键点击位置: ({position.X}, {position.Y})");
        
        // 尝试删除点击位置的图形
        DeleteShapeAtPosition(position);
    }
    
    // 删除指定位置的图形
    private void DeleteShapeAtPosition(Point position)
    {
        if (_layerManager.SelectedLayer == null)
            return;
            
        Console.WriteLine($"尝试删除位置 ({position.X}, {position.Y}) 的图形");
        
        // 查找并删除点击位置的图形
        foreach (var shape in _selectableShapes.ToList()) // 使用ToList()创建副本以避免在迭代时修改集合
        {
            // 测试是否点击到了图形
            if (shape.HitTest(position))
            {
                Console.WriteLine($"找到要删除的图形: {shape.Element.GetType().Name}");
                
                // 创建删除命令
                var deleteCommand = new DeleteShapeCommand(
                    _layerManager.SelectedLayer,
                    shape.Element,
                    shape,
                    _layerManager,
                    _selectableShapes,
                    () => {
                        // 如果删除的是当前选中的图形，清除选中状态
                        if (_selectedShape == shape)
                        {
                            _selectedShape = null;
                            UpdateDeleteButtonState();
                        }
                        
                        StatusText.Text = "已删除图形";
                        Console.WriteLine("图形删除成功");
                    }
                );
                
                // 执行删除命令
                _commandManager.ExecuteCommand(deleteCommand);
                
                return;
            }
        }
        
        Console.WriteLine("未找到可删除的图形");
    }

    // 图形选中事件处理
    private void Shape_SelectionChanged(object? sender, AvaloniaDrawingPad.Models.ShapeSelectionChangedEventArgs e)
    {
        if (e.IsSelected)
        {
            // 如果有新图形被选中，先取消其他所有图形的选择
            if (sender is SelectableShape selectedShape && selectedShape != _selectedShape)
            {
                // 取消之前选中图形的选择状态（不触发事件）
                if (_selectedShape != null)
                {
                    // 临时取消事件订阅以避免循环
                    _selectedShape.SelectionChanged -= Shape_SelectionChanged;
                    _selectedShape.IsSelected = false;
                    if (_selectedShape != null)
                        _selectedShape.SelectionChanged += Shape_SelectionChanged;
                }
                
                // 更新当前选中的图形
                _selectedShape = selectedShape;
                StatusText.Text = $"已选择图形: {_selectedShape.Element.GetType().Name}";
                Console.WriteLine($"通过事件选中图形: {_selectedShape.Element.GetType().Name}");
            }
        }
        else if (sender is SelectableShape unselectedShape && unselectedShape == _selectedShape)
        {
            // 如果当前选中的图形被取消选择
            _selectedShape = null;
            StatusText.Text = "就绪 - 选择模式";
            Console.WriteLine("通过事件取消选中图形");
        }
        
        // 更新删除按钮状态
        UpdateDeleteButtonState();
    }

    // 设置所有图形的选择功能启用状态
    private void SetShapesSelectionEnabled(bool enabled)
    {
        foreach (var shape in _selectableShapes)
        {
            shape.SelectionEnabled = enabled;
        }
    }

    // 添加保存为图片的功能
    private async void SaveButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs? e)
    {
        await SaveDrawingAsImageAsync();
    }
    
    // 保存绘图为PNG图片
    private async Task<bool> SaveDrawingAsImageAsync()
    {
        try
        {
            // 获取保存文件对话框
            var storageProvider = StorageProvider;
            var saveFileDialog = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
            {
                Title = "导出为图片",
                SuggestedFileName = $"绘图_{DateTime.Now:yyyyMMdd_HHmmss}",
                FileTypeChoices = new[]
                {
                    new FilePickerFileType("PNG图片")
                    {
                        Patterns = new[] { "*.png" },
                        MimeTypes = new[] { "image/png" }
                    }
                }
            });

            if (saveFileDialog != null)
            {
                // 创建RenderTargetBitmap来渲染画布
                var pixelSize = new PixelSize((int)MainCanvas.Bounds.Width, (int)MainCanvas.Bounds.Height);
                var size = new Size(MainCanvas.Bounds.Width, MainCanvas.Bounds.Height);
                
                using (var renderBitmap = new RenderTargetBitmap(pixelSize, new Vector(96, 96)))
                {
                    renderBitmap.Render(MainCanvas);
                    
                    // 保存为PNG
                    using (var stream = await saveFileDialog.OpenWriteAsync())
                    {
                        renderBitmap.Save(stream);
                    }
                }
                
                StatusText.Text = "绘图已导出为图片";
                return true;
            }
            
            return false;
        }
        catch (Exception ex)
        {
            StatusText.Text = $"导出图片失败: {ex.Message}";
            return false;
        }
    }
    
    // 颜色选择事件
    private void ColorSelector_SelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (ColorSelector.SelectedItem is ComboBoxItem selectedItem && selectedItem.Tag is string colorName)
        {
            switch (colorName)
            {
                case "Black":
                    _currentBrush = Brushes.Black;
                    break;
                case "Red":
                    _currentBrush = Brushes.Red;
                    break;
                case "Blue":
                    _currentBrush = Brushes.Blue;
                    break;
                case "Green":
                    _currentBrush = Brushes.Green;
                    break;
                case "Yellow":
                    _currentBrush = Brushes.Yellow;
                    break;
                default:
                    _currentBrush = Brushes.Black;
                    break;
            }
        }
    }
    
    // 线条粗细选择事件
    private void ThicknessSelector_SelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (ThicknessSelector.SelectedItem is ComboBoxItem selectedItem && selectedItem.Tag is string thicknessStr)
        {
            if (double.TryParse(thicknessStr, out double thickness))
            {
                _currentThickness = thickness;
            }
        }
    }

    // 确认未保存的更改
    private async Task<bool> ConfirmUnsavedChanges()
    {
        var confirmResult = await MessageBoxManager.GetMessageBoxStandard(
               "未保存的更改",
               "您有未保存的更改，是否保存？",
               ButtonEnum.YesNoCancel,
                MsBox.Avalonia.Enums.Icon.Warning
           ).ShowWindowDialogAsync(this);

        if (confirmResult == ButtonResult.Yes)
        {
            // 保存当前项目
            bool saved = await SaveCurrentProject();
            return saved; // 如果保存失败，取消操作
        }
        else if (confirmResult == ButtonResult.No)
        {
            return true; // 不保存，继续操作
        }
        else // Cancel
        {
            return false; // 取消操作
        }
    }

    // 显示错误消息框
    private void ShowErrorMessage(string title, string message)
    {
        // 简单实现：在状态栏显示错误
        StatusText.Text = $"错误: {message}";
        MessageBoxManager.GetMessageBoxStandard(
                    "保存失败",
                    "保存项目时发生错误。",
                    ButtonEnum.Ok,
                     MsBox.Avalonia.Enums.Icon.Error
                     ).ShowWindowDialogAsync(this);
    }

    // 命令管理器状态变更事件
    private void CommandManager_StateChanged(object? sender, EventArgs e)
    {
        // 更新UI以反映命令状态
        UpdateUndoRedoState();
    }

    // 更新撤销/重做按钮状态
    private void UpdateUndoRedoState()
    {
        if (UndoMenuItem != null)
        {
            UndoMenuItem.IsEnabled = _commandManager.CanUndo;
            if (_commandManager.CanUndo)
            {
                UndoMenuItem.Header = $"撤销 {_commandManager.UndoDescription}";
            }
            else
            {
                UndoMenuItem.Header = "撤销";
            }
        }
        
        if (RedoMenuItem != null)
        {
            RedoMenuItem.IsEnabled = _commandManager.CanRedo;
            if (_commandManager.CanRedo)
            {
                RedoMenuItem.Header = $"重做 {_commandManager.RedoDescription}";
            }
            else
            {
                RedoMenuItem.Header = "重做";
            }
        }
    }
    
    // 撤销按钮点击事件
    private void Undo_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        if (_commandManager.Undo())
        {
            StatusText.Text = $"已撤销: {_commandManager.RedoDescription}";
            
            // 更新选中状态
            if (_selectedShape != null && !_selectableShapes.Contains(_selectedShape))
            {
                _selectedShape = null;
                UpdateDeleteButtonState();
            }
        }
    }
    
    // 重做按钮点击事件
    private void Redo_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        if (_commandManager.Redo())
        {
            StatusText.Text = $"已重做: {_commandManager.UndoDescription}";
        }
    }
}